package com.richapp.launcher.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jack.util.hex.HexUtil;
import com.jack.util.string.StringUtil;
import com.richapp.launcher.R;
import com.richapp.launcher.busevent.EventServiceDestroy;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.ConditionSensorModelDao;
import com.richapp.launcher.database.system.dao.ConditionStatusModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelHistoryDao;
import com.richapp.launcher.database.system.dao.SceneModelDao;
import com.richapp.launcher.database.system.dao.SystemValueModelDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.ConditionSensorModel;
import com.richapp.launcher.database.system.mode.ConditionStatusModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.database.system.mode.SceneModel;
import com.richapp.launcher.database.system.mode.SystemValueModel;
import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.mobile.message.DeviceStatusReply;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.scene.Scene;
import com.richapp.launcher.scene.SceneServer;
import com.richapp.launcher.scene.conditions.sensor.SceneSensorAirConditions;
import com.richapp.launcher.scene.conditions.sensor.SceneSensorAlarmConditions;
import com.richapp.launcher.scene.conditions.sensor.SceneSensorCo2Conditions;
import com.richapp.launcher.scene.conditions.sensor.SceneSensorLightConditions;
import com.richapp.launcher.scene.conditions.sensor.SceneSensorPm25Conditions;
import com.richapp.launcher.scene.conditions.sensor.SceneSensorTemperatureHumidityConditions;
import com.richapp.launcher.serialport.gateway.ControlInstructionMessage;
import com.richapp.launcher.serialport.gateway.GatewayMessageListner;
import com.richapp.launcher.serialport.gateway.GatewayServer;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.launcher.serialport.gateway.command.AddCmd;
import com.richapp.launcher.serialport.gateway.command.ControlDeviceCmd;
import com.richapp.launcher.serialport.gateway.command.InfraredControlCmd;
import com.richapp.launcher.serialport.gateway.command.InfraredStudyCmd;
import com.richapp.launcher.serialport.gateway.command.QueryCmd;
import com.richapp.launcher.utils.Constants;
import com.richapp.launcher.utils.Tools;
import com.richapp.net.util.HexTool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.igexin.sdk.GTServiceManager.context;

/**
 * Created by jack on 2015/5/5 0005.
 */
public class GatewayService extends Service implements GatewayMessageListner {
    private List<DeviceModel> list = new ArrayList<>();
    private static final String TAG = GatewayService.class.getName();
    private GatewayServer gatewayServer = null;
    private Map<String,Scene> sceneMap = null;
    final Handler handler=new Handler();
    private  Runnable runnable;
    public  boolean starSceneFlag=true;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        gatewayServer = GatewayServer.getInstance();
        gatewayServer.setContext(this);
        gatewayServer.setDeviceName(getResources().getString(R.string.gateway_device_name));
        gatewayServer.setDeviceBit(getResources().getInteger(R.integer.gateway_device_bit));
        gatewayServer.setDeviceFlag(getResources().getInteger(R.integer.gateway_device_flag));
        gatewayServer.setMessageListner(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                gatewayServer.start();
            }
        }).start();
        //保持服务
        Notification notification = new Notification();
        startForeground(6, notification);
        //Toast.makeText(this, "网关服务启动", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        gatewayServer.stop();

        EventBus.getDefault().post(new EventServiceDestroy(GatewayService.class));
    }

    /**
     * 串口信息处理
     */
    @Override
    public void messageReceived(String hexData) {
        if (GatewaytConstant.INSTRUCTION_ERRO_STR.equals(hexData)) {
            //ERRO
            Log.d(TAG, "收到结果ERRO");
            //校对指令令牌生效
            GatewayServer.setClearFlag(true);

            if (GatewayServer.getLastMessage() != null) {
                //设置指令发送结果
                GatewayServer.getLastMessage().setInstructionResult(GatewaytConstant.INSTRUCTION_RESULT_ERRO);
                //上一次指令失败次数+1
                GatewayServer.getLastMessage().setFailCount(GatewayServer.getLastMessage().getFailCount() + 1);

                //设置指令结束时间
                GatewayServer.getLastMessage().setStopTime(System.currentTimeMillis());
            }

        } else if (GatewaytConstant.INSTRUCTION_BUSY_STR.equals(hexData)) {
            //BUSY
            Log.d(TAG, "收到结果BUSY");
            if (GatewayServer.getLastMessage() != null) {
                //设置指令发送结果
                GatewayServer.getLastMessage().setInstructionDoResult(GatewaytConstant.INSTRUCTION_DO_RESULT_BUSY);
                //繁忙情况下，认为上一次指令发送失败
                //上一次指令失败次数+1
                GatewayServer.getLastMessage().setFailCount(GatewayServer.getLastMessage().getFailCount() + 1);

                //设置指令结束时间
                GatewayServer.getLastMessage().setStopTime(System.currentTimeMillis());
            }

        } else if (GatewaytConstant.INSTRUCTION_FAIL_STR.equals(hexData)) {
            Log.d(TAG, "收到设备动作FAIL");
            System.out.println("指令信息:" + GatewayServer.getLastMessage());

            if (GatewayServer.getLastMessage() != null) {
                //设置指令发送结果
                GatewayServer.getLastMessage().setInstructionDoResult(GatewaytConstant.INSTRUCTION_DO_RESULT_FAIL);

                //失败也认为上次指令失败
                GatewayServer.getLastMessage().setFailCount(GatewayServer.getLastMessage().getFailCount() + 1);

                //设置指令结束时间
                GatewayServer.getLastMessage().setStopTime(System.currentTimeMillis());
            }

        } else if (GatewaytConstant.INSTRUCTION_PROOFREADING_STR.equals(hexData)) {
            Log.d(TAG, "收到校对指令");

        } else {
            //第二步，校验数据
            if (hexData.startsWith(GatewaytConstant.INSTRUCTION_HEAD)) {
                if (GatewayServer.getLastMessage() == null || GatewaytConstant.INSTRUCTION_DO_RESULT_DATA.equals(GatewayServer.getLastMessage().getInstructionDoResult())) {
                    analysisSystemInstruction(hexData);
                } else {
                    //根据指令类型确定指令结束时间
                    if (GatewaytConstant.INSTRUCTION_FLAG_ADD_ALL.equals(GatewayServer.getLastMessage().getInstructionFlag())) {
                        if (GatewaytConstant.INSTRUCTION_PACKAGE_TYPE_3_STR.equals(hexData.substring(4, 6))) {
                            //设置指令结束时间
                            GatewayServer.getLastMessage().setStopTime(System.currentTimeMillis());
                            //设置指令结果
                            GatewayServer.getLastMessage().setInstructionDoResult(GatewaytConstant.INSTRUCTION_DO_RESULT_DATA);
                        }
                    } else {
                        //设置指令结束时间
                        GatewayServer.getLastMessage().setStopTime(System.currentTimeMillis());
                        //设置指令结果
                        GatewayServer.getLastMessage().setInstructionDoResult(GatewaytConstant.INSTRUCTION_DO_RESULT_DATA);
                    }

                    if(GatewaytConstant.INSTRUCTION_FLAG_INFRARED_STUDY.equals(GatewayServer.getLastMessage().getInstructionFlag())
                            || GatewaytConstant.INSTRUCTION_FLAG_INFRARED_CONTROL.equals(GatewayServer.getLastMessage().getInstructionFlag())){
                        analysisFraredInstruction(GatewayServer.getLastMessage());
                    }else{
                        //解析数据
                        analysisUserInstruction(hexData);
                    }
                }
            }
        }
    }

    /**
     * 红外指令解析
     * @param message
     */
    public void analysisFraredInstruction(ControlInstructionMessage message){
        if(GatewaytConstant.INSTRUCTION_FLAG_INFRARED_STUDY.equals(message.getInstructionFlag())){
            InfraredStudyCmd.getInstance(this).analyticalInfrared(message);
        }else if(GatewaytConstant.INSTRUCTION_FLAG_INFRARED_CONTROL.equals(message.getInstructionFlag())){
            InfraredControlCmd.getInstance().analyticalInfrared(message);
        }
    }

    /**
     * 解析用户指令
     *
     * @param instruction 用户指令
     */
    public void analysisUserInstruction(String instruction) {
        String flag = GatewayServer.getLastMessage().getInstructionFlag();

        if (GatewaytConstant.INSTRUCTION_FLAG_ADD_ALL.equals(flag)) {
            AddCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_ADD_ONE.equals(flag)) {
            AddCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_RESET_ALL.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_UPGRADE.equals(flag)) {

        } else if (GatewaytConstant.INSTRUCTION_FLAG_SWITCH.equals(flag)) {
            ControlDeviceCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_ADJUST.equals(flag)) {

        } else if (GatewaytConstant.INSTRUCTION_FLAG_QUERY.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_OPEN_ONE.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_OPEN_ALL.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_CLOSE_ONE.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_CLOSE_ALL.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_STOP.equals(flag)) {
            QueryCmd.getInstance().analyticalCmd(instruction);
        } else if (GatewaytConstant.INSTRUCTION_FLAG_READ.equals(flag)) {

        } else if (GatewaytConstant.INSTRUCTION_FLAG_SCENESWITCH.equals(flag)) {

        }

        EventBus.getDefault().post(Constants.ACTION_NOTIFY_MAIN_ACTIVITY);


}

    /**
     * 解析系统自动上报数据
     *  FF 00 12 00 1C 01 01 00 67 FE 00 1F 02 00 03 00 00 02 B8
     * @param systemInstruction
     */
    public void analysisSystemInstruction(String systemInstruction) {

        if("FE".equals(systemInstruction.substring(16, 18))){ //所有设备上报离线都抛掉
            return;
        }
        String deviceId = systemInstruction.substring(8, 10);
        if(!GatewaytConstant.getDeviceTypeMap().containsKey(deviceId)) {
            return;
        }

        BoxModel bm = new BoxModelDao(this).getCurrentBox();
        String currentBoxCpuId= bm.getBoxCpuId();
        DeviceModelDao dmd = new DeviceModelDao(this);
        DeviceModel dm = null;
        DeviceModel dm2 = null;
        DeviceModel dm3 = null;
        DeviceStatusReply deviceStatusReply = null;
        String busyStatus = systemInstruction.substring(10, 12);
        String deviceNumber = null;
        String way = "01";
        if (GatewaytConstant.ID_TYPE_CARBON_DIOXIDE_STR.equals(deviceId)) {
            deviceNumber = systemInstruction.substring(10, 14);
        } else {
            if (GatewaytConstant.getMiltiWayMap().containsKey(deviceId)) {
                deviceNumber = systemInstruction.substring(12, 14);
                way = systemInstruction.substring(14, 16);
            } else {
                deviceNumber = systemInstruction.substring(12, 16);
            }
        }
        String version = systemInstruction.substring(16, 18);
        String onlineStatus = systemInstruction.substring(18, 20);
        String deviceStatus = systemInstruction.substring(20, 22);
        String signal = systemInstruction.substring(22, 24);
        String deviceAutoReset = systemInstruction.substring(26, 34);

        boolean analysisFlag = false;


        //FF 00 12 0x06  0683    06 00  BD  01       4F  69   02 50 BB 00 00 05
        //               光照     PM2.5     空气质量       湿度 温度
        if (GatewaytConstant.ID_TYPE_CARBON_DIOXIDE_STR.equals(deviceId)) { //传感器四合一,环境探测器
            Double temperature = 0.0;
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm==null || "".equals(dm)){
                Log.v(TAG, "收到探测器数据||设备可能已被移除数据库");
                return;
            }

            dm.setVersion("");
            //PM2.5
            Log.v("info", "收到PM2.5传感数据");

            dm.setPm25(HexTool.HexToInt(systemInstruction.substring(14, 18)));
            GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName(), dm.getPm25() + "");


            //空气质量
            Log.v("info", "收到空气质量传感数据");
            dm.setAriQuality(HexTool.HexToInt(systemInstruction.substring(20, 22)));
            GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName(), getAirValue(dm.getAriQuality()));

            //温湿度
            Log.v("info", "收到温湿度传感数据");
            //过滤掉FFFFFF时候的值底层硬件问题
           if ("FFFFFF".equals(systemInstruction.substring(24,30))){

               Log.v("FFFFFF", "温度传感器异常"+systemInstruction.substring(24,30));
               GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName() + "|温度", dm.getTemperature() + "");
               GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName() + "|湿度", dm.getHumidity() + "%");

           }else {
               String symbol = systemInstruction.substring(26, 27);
               int t1 = HexUtil.HexToInt(systemInstruction.substring(27, 28)) * 10;
               int t2 = HexUtil.HexToInt(systemInstruction.substring(28, 29));
               String ts3 = systemInstruction.substring(29, 30);
               int t3 = HexUtil.HexToInt(ts3);
               String total = "0".equals(symbol) ? "" + (t1 + t2) + "." + t3 : "-" + (t1 + t2) + "." + t3;
               dm.setTemperature(Double.valueOf(total) -5);
               temperature= (Double.valueOf(total) -5);//检测情景判断条件
               dm.setHumidity(HexUtil.HexToInt(systemInstruction.substring(24, 26)));


               GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName() + "|温度", dm.getTemperature() + "");
               GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName() + "|湿度", dm.getHumidity() + "%");

           }

            //光照
            Log.v("info", "收到光照传感数据");
            dm.setSunLight(HexTool.HexToInt(systemInstruction.substring(30, 34)));
            analysisFlag = true;
            GatewayServer.getInstance().broadCastSensorStatus(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName(), getLightValue(dm.getSunLight()));

            Log.d(getClass().getName(),"设备信息："+ dm.toString());
            //通知界面刷新
            EventBus.getDefault().post(Constants.ACTION_NOTIFY_MAIN_ACTIVITY);

            int pm25=  HexTool.HexToInt(systemInstruction.substring(14, 18));
            int sunLight=HexTool.HexToInt(systemInstruction.substring(30, 34));
            int Humidity=HexUtil.HexToInt(systemInstruction.substring(24, 26));
            int ariQuality=HexTool.HexToInt(systemInstruction.substring(20, 22));

            if (Humidity!=255){//探测器情景检测条件把湿度255的错误数据抛弃不处理
                SensorSceneList(pm25,sunLight,Humidity,ariQuality,temperature,currentBoxCpuId,deviceNumber,way);
            }
            dmd.add(dm);
        } else if (GatewaytConstant.ID_TYPE_THE_SOCKET_STR.equals(deviceId)) {
            //插座

            analysisFlag = true;
        } else if (
//                GatewaytConstant.ID_TYPE_NOMAL_LIGHT_STR.equals(deviceId)
                   GatewaytConstant.ID_TYPE_LAMP_HOLDER_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_POWER_STR.equals(deviceId)
//                || GatewaytConstant.ID_TYPE_NORMAL_SWITCH_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_DIMMING_SWITCH_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_LAMP_HOLDER_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_ONE_CASE_NORMAL_SWITCH_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_TWO_CASE_NORMAL_SWITCH_STR.equals(deviceId)
//                || GatewaytConstant.ID_TYPE_THREE_CASE_NORMAL_SWITCH_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_FOUR_CASE_NORMAL_SWITCH_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_ONE_CASE_DIMMING_SWITCH_STR.equals(deviceId)
                || GatewaytConstant.ID_TYPE_TWO_CASE_DIMMING_SWITCH_STR.equals(deviceId)) {
            //灯座
            deviceNumber = systemInstruction.substring(10, 12);
            way = systemInstruction.substring(12, 14);
            deviceStatus = systemInstruction.substring(14, 16);
            onlineStatus = systemInstruction.substring(18, 20);
            signal = systemInstruction.substring(22, 24);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm == null){
                return;
            }
            dm.setDeviceNumber(deviceNumber);
            dm.setWay(way);
            dm.setDeviceStatus(deviceStatus);
            dm.setOnlineStatus(onlineStatus);
            dm.setSignal(signal);

            analysisFlag = true;

        }else if (GatewaytConstant.ID_TYPE_NOMAL_LIGHT_STR.equals(deviceId)) {
            //普通灯
            deviceNumber = systemInstruction.substring(10, 12);
            way = "00";
            deviceStatus = systemInstruction.substring(14, 16);
            onlineStatus = systemInstruction.substring(18, 20);
            signal = systemInstruction.substring(22, 24);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm == null){
                return;
            }
            dm.setDeviceNumber(deviceNumber);
            dm.setWay(way);
            dm.setDeviceStatus(deviceStatus);
            dm.setOnlineStatus(onlineStatus);
            dm.setSignal(signal);
            analysisFlag = true;
            dmd.add(dm);
        }else if (GatewaytConstant.getMiltiWayMap().containsKey(deviceId)) {
            //普通触摸开关 FF 00 12 00 1C 01 01 FF 67 BD 00 4F 02 FF 03 00 0004A5
            analyticalCmd(systemInstruction);
            analysisFlag = false;
        } else if (GatewaytConstant.ID_TYPE_DOOR_LOCK_STR.equals(deviceId)) {
            //门锁 FF 00 12 00 0E 02 00 73 67 BD FF 4F 00 00 00 00 00 0406
            String statusPower=systemInstruction.substring(24,26);
            String statusStr = systemInstruction.substring(14, 16);
            deviceNumber=systemInstruction.substring(10,12);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm==null){
                return;
            }

            if (statusStr.endsWith("1")) {          // 无门磁 方舌进 --》门开
                dm.setLockKeyStatus(statusStr);
                dm.setPowerStatus(statusPower);
                UserServer userServer= UserServer.getInstance();
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("systemAlarmFlag","false");
                jsonObject.put("boxCpuId",bm.getBoxCpuId());
                jsonObject.put("userName",bm.getUserName());
                String clientId="";
                userServer.doSetSystemAlarmFlag(clientId,jsonObject);
                Log.v("门锁状态",""+statusStr);

            } else if (statusStr.endsWith("5")) {    //有门磁  方舌进  --》不一定锁门因为没有斜舌信号  关门
                dm.setLockKeyStatus(statusStr);
                Log.v("门锁状态",""+statusStr);

            } else if (statusStr.endsWith("3")) {    //无门磁 方舌出 --》门开
                dm.setLockKeyStatus(statusStr);
                dm.setPowerStatus(statusPower);
                Log.v("门锁状态",""+statusStr);

            }else  if(statusStr.endsWith("7")){       //有门磁  方舌出 --》门反锁
                dm.setLockKeyStatus(statusStr);
                dm.setPowerStatus(statusPower);
                Log.v("门锁状态",""+statusStr);
                UserServer userServer= UserServer.getInstance();
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("systemAlarmFlag","true");
                jsonObject.put("boxCpuId",bm.getBoxCpuId());
                jsonObject.put("userName",bm.getUserName());
                String clientId="";
                userServer.doSetSystemAlarmFlag(clientId,jsonObject);

            }else {
                return;
            }
            alarm(dm);
            analysisFlag = true;
            dmd.add(dm);
        } else if (GatewaytConstant.ID_TYPE_CURTAIN_STR.equals(deviceId)) {
            //窗帘

            analysisFlag = true;
        } else if (GatewaytConstant.ID_TYPE_ALARM_SMOKE_STR.equals(deviceId)) {
            //烟感
            Log.v("info", "收到烟感传感数据");
            alarm(dm);
            analysisFlag = true;
            GatewayServer.getInstance().broadCastSensorAlarm(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName());
        } else if (GatewaytConstant.ID_TYPE_ALARM_PEOPLE_SENSE_STR.equals(deviceId)) {
            //人感 ：FF 00 12 00 0D 01 00 01 67 BD FF 4F 00 03 FF 00 00 04 94
            Log.v("info", "收到人感传感数据");
            deviceNumber = systemInstruction.substring(10,12);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if (dm==null || "".equals(dm)){
                Log.v(TAG, "人感器已经被删除后没有被重置");
                return;
            }
            String olldStatus=dm.getDeviceStatus();
            deviceStatus = systemInstruction.substring(14,16);
            dm.setDeviceStatus(deviceStatus);
            dm.setPowerStatus(systemInstruction.substring(24,26));
            alarm(dm);
            analysisFlag = true;

//            if(!deviceStatus.equals(olldStatus)){
//                dmd.add(dm);
//                if(checkSceneList(deviceStatus,deviceNumber,deviceId)){          //*****判断情景条件是否满足如果满足则做一次情景检测
//                    SceneServer.getInstance().setSceneOpenFlag(true);
//                    SceneServer.getInstance().startStatusScene();
//                }
//            }

        } else if (GatewaytConstant.ID_TYPE_ALARM_COMBUSTIBLE_GAS_STR.equals(deviceId)) {
            //可燃气
            Log.v("info", "收到可燃气传感数据");
            alarm(dm);
            analysisFlag = true;

            GatewayServer.getInstance().broadCastSensorAlarm(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName());
        } else if (GatewaytConstant.ID_TYPE_ALARM_SWITCH_STR.equals(deviceId)) {
            //开关报警
            Log.v("info", "收到开关报警传感数据");
            alarm(dm);
            analysisFlag = true;
            GatewayServer.getInstance().broadCastSensorAlarm(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName());
            dmd.add(dm);
        } else if (GatewaytConstant.ID_TYPE_ALARM_EMERGENCY_STR.equals(deviceId)) {
            //紧急报警
            Log.v(TAG, "收到紧急报警传感数据");
            deviceNumber=systemInstruction.substring(10,12);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm==null){
                return;
            }
            dm.setDeviceStatus(systemInstruction.substring(14,16));
            dm.setPowerStatus(systemInstruction.substring(24,26));
            dm.setVersion("");
            alarm(dm);
            analysisFlag = true;

            GatewayServer.getInstance().broadCastSensorAlarm(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName());

        } else if (GatewaytConstant.ID_TYPE_SECURITY_EQUIPMENT_STR.equals(deviceId)) {
            //门磁
//            FF 00 12 00 17  00 00 FF 67 BD FF 4F 02 03 FF 00 00 05 9D
//            FF 00 12 00 17  01 00 C0 67 BD FF 4F 00 03 FF 00 00 05 5D
            Log.v("info", "收到门磁数据");
            deviceNumber=systemInstruction.substring(10,12);
            if(deviceNumber=="00"){
                return;
            }
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm==null || "".equals(dm)){
                Log.v(TAG, "网关板不存相应设备");
                return;
            }else {
                dm.setVersion("");
                deviceStatus = systemInstruction.substring(14, 16);
                dm.setDeviceStatus(deviceStatus);
                String powerStatus = systemInstruction.substring(24, 26);
                dm.setPowerStatus(powerStatus);
                alarm(dm);
                analysisFlag = true;
                dmd.add(dm);
                if(checkSceneList(deviceStatus,deviceNumber,deviceId)){          //*****判断情景条件是否满足如果满足则做一次情景检测
                    SceneServer.getInstance().setSceneOpenFlag(true);
//                    SceneServer.getInstance().startStatusScene();

                }
            }
        }else if (GatewaytConstant.ID_TYPE_NORMAL_SWITCH_STR.equals(deviceId)) {
            //情景普通开关：FF 00 12 00 10 01 00 08 67 BD FF 4F FF 03 FF 00 00 05 9D
            Log.v(TAG, "收到情景开关传感数据");
            deviceNumber=systemInstruction.substring(10,12);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);
            if(dm==null){
                return;
            }
            dm.setVersion("");
            deviceStatus = systemInstruction.substring(14, 16);
            dm.setDeviceStatus(deviceStatus);
            String powerStatus = systemInstruction.substring(24, 26);
            dm.setPowerStatus(powerStatus);
            alarm(dm);
            deviceStatusReply=new DeviceStatusReply();
            deviceStatusReply.setType(75);
            analysisFlag = true;
            SceneModelDao sceneModelDao=new SceneModelDao(this);
            SceneModel sceneModel= sceneModelDao.getSceneModelByDeviceNumberAndSceneKey(deviceNumber,deviceStatus);
            if (sceneModel!=null || "".equals(sceneModel)){
                String sceneName = sceneModel.getSceneName();
                SceneServer.getInstance().checkPasstiveScene(sceneName);//根据情景名触发相应的情景
            }else {
                return;
            }

        }else {
            Log.v("warn", "未添加的自动解析类型:" + deviceId);
        }


        if (analysisFlag) {
            dmd.add(dm);
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(), deviceId, deviceNumber, way);

            if(dm!=null){
            //计算电量
            new DeviceModelHistoryDao(this).addModelHisotry(dm);
            }
            List<DeviceModel> list = new ArrayList<DeviceModel>();
            list.add(dm);

            if (deviceStatusReply==null){
                deviceStatusReply=new DeviceStatusReply();
            }
            String userName=new BoxModelDao(this).getCurrentBox().getUserName();
            deviceStatusReply.setUserName(userName);
            deviceStatusReply.setDeviceStatus(list);
            deviceStatusReply.setCurrentBoxCpuId(new BoxModelDao(this).getCurrentBox().getBoxCpuId());
            if (userName==null) {
                deviceStatusReply.setUserName(new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox().getUserName());
            }
            JSONObject jsonObject = (JSONObject) JSON.toJSON(deviceStatusReply);

            //发送所有当前手机
            UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

            if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
                jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());

            }

        }

    }



    public void alarm(DeviceModel dm) {
        dm.setLastAlarmTime(System.currentTimeMillis());
        String alarmFlag = null;
        SystemValueModelDao systemValueModelDao=null;
        try {
            alarmFlag = new SystemValueModelDao(this).getByName(dm.getBoxCpuId(), GatewaytConstant.SYSTEM_KEY_NAME_ALARM_FLAG).getValue();
            if (alarmFlag==null){
                SystemValueModel systemValueModel=new SystemValueModel();
                systemValueModel.setBoxCpuId(dm.getBoxCpuId());
                systemValueModel.setValue("false");
                systemValueModel.setName("systemAlarmFlag");
                systemValueModelDao.add(systemValueModel);
            }
        if ("true".equals(alarmFlag) || "true".equals(dm.getAlarmFlag())) {
            if (GatewaytConstant.ID_TYPE_ALARM_PEOPLE_SENSE_STR.equals(dm.getDeviceId())
                    || (GatewaytConstant.ID_TYPE_SECURITY_EQUIPMENT_STR.equals(dm.getDeviceId()) && "00".equals(dm.getDeviceStatus()))) {
                GatewayServer.getInstance().broadCastSensorAlarm(Tools.getStringValue(dm.getRoomName()) + dm.getDeviceName());
                GPIOServer.getInstance().alarmBeep();
            } else {
                GPIOServer.getInstance().alarmBeep();
            }
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getCo2Value(int value) {
        String result = "中";
        if (value <= 400) {
            result = "优";
        } else if (value > 400 && value <= 800) {
            result = "良";
        } else if (value > 800 && value <= 1200) {
            result = "中";
        } else if (value > 1200 && value <= 1600) {
            result = "差";
        } else if (value > 1600 && value <= 2000) {
            result = "很差";
        } else if (value > 2000) {
            result = "非常差";
        }
        return result;
    }

    public String getAirValue(int value) {
        String result = "良";
        if (value <= 50) {
            result = "优";
        } else if (value > 50 && value <= 100) {
            result = "良";
        } else if (value > 100 && value <= 150) {
            result = "轻度污染";
        } else if (value > 150 && value <= 200) {
            result = "中度污染";
        } else if (value > 200 && value <= 300) {
            result = "重度污染";
        } else if (value > 300) {
            result = "严重污染";
        }
        return result;
    }

    public String getLightValue(int value) {
        String result = "亮";
        if (value <= 8191) {
            result = "最暗";
        } else if (value > 8191 && value <= 16383) {
            result = "很暗";
        } else if (value > 16383 && value <= 24575) {
            result = "暗";
        } else if (value > 24575 && value <= 32767) {
            result = "微亮";
        } else if (value > 32767 && value <= 40959) {
            result = "亮";
        } else if (value > 40959 && value <= 49151) {
            result = "明亮";
        } else if (value > 49151 && value <= 57343) {
            result = "很亮";
        } else if (value > 57343) {
            result = "非常亮";
        }
        return result;
    }

    private void analyticalCmd(String upStreamCmd) {

        String deviceStatus="00";
        String deviceStatus2="00";
        String deviceStatus3="00";
        String deviceId = upStreamCmd.substring(8, 10);
        String Number = upStreamCmd.substring(10, 12);
        String way = upStreamCmd.substring(12, 14);
        deviceStatus = upStreamCmd.substring(14, 16);


        String way2 = null;
        String way3 = null;
        String way4 = null;


        String deviceStatus4 = null;

        String ifAnyone = "false";

        if(GatewaytConstant.getMiltiWayMap().containsKey(deviceId)){
            ifAnyone = upStreamCmd.substring(20, 22);

            if(GatewaytConstant.ID_TYPE_ONE_CASE_NORMAL_SWITCH_STR.equals(deviceId)){


            }else if(GatewaytConstant.ID_TYPE_TWO_CASE_NORMAL_SWITCH_STR.equals(deviceId)){
                way2 = upStreamCmd.substring(24, 26);
                deviceStatus2 = upStreamCmd.substring(26, 28);

            }else if(GatewaytConstant.ID_TYPE_THREE_CASE_NORMAL_SWITCH_STR.equals(deviceId)){
                way2 = upStreamCmd.substring(24, 26);
                deviceStatus2 = upStreamCmd.substring(26, 28);
                way3 = upStreamCmd.substring(28, 30);
                deviceStatus3 = upStreamCmd.substring(30, 32);

            }else if(GatewaytConstant.ID_TYPE_FOUR_CASE_NORMAL_SWITCH_STR.equals(deviceId)){
                way2 = upStreamCmd.substring(24, 26);
                deviceStatus2 = upStreamCmd.substring(26, 28);
                way3 = upStreamCmd.substring(28, 30);
                deviceStatus3 = upStreamCmd.substring(30, 32);

            }
        }

        String onlineStatus = upStreamCmd.substring(18, 20);

        String signal = upStreamCmd.substring(22, 24);

        BoxModel bm = new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox();
        if(GatewaytConstant.getDeviceTypeMap().containsKey(deviceId)){
            DeviceModel dm;
            DeviceModel dm2;
            DeviceModel dm3;
            DeviceModel dm4;

            DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, Number,way);
            if(dm != null){
                dm.setDeviceStatus(deviceStatus);
                dm.setSignal(signal);
                dm.setOnlineStatus(onlineStatus);
                dm.setIfAnyone(ifAnyone);
                dmd.add(dm);

                dm = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),dm.getDeviceId(), dm.getDeviceNumber(),way);
                list.add(dm);

                //统计耗电量
                new DeviceModelHistoryDao(GatewayServer.getInstance().getContext()).addModelHisotry(dm);
            }

            if(!StringUtil.isNullOrEmpty(way2)){
                dm2 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, Number,way2);
                if(dm2 != null){
                    dm2.setDeviceStatus(deviceStatus2);
                    dm2.setSignal(signal);
                    dm2.setOnlineStatus(onlineStatus);
                    dm2.setIfAnyone(ifAnyone);
                    dmd.add(dm2);

                    dm2 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),dm2.getDeviceId(), dm2.getDeviceNumber(),way2);
                    list.add(dm2);

                    //统计耗电量
                    new DeviceModelHistoryDao(GatewayServer.getInstance().getContext()).addModelHisotry(dm2);
                }
            }

            if(!StringUtil.isNullOrEmpty(way3)){
                dm3 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, Number,way3);
                if(dm3 != null){
                    dm3.setDeviceStatus(deviceStatus3);
                    dm3.setSignal(signal);
                    dm3.setOnlineStatus(onlineStatus);
                    dm3.setIfAnyone(ifAnyone);
                    dmd.add(dm3);

                    dm3 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),dm3.getDeviceId(), dm3.getDeviceNumber(),way3);
                    list.add(dm3);

                    //统计耗电量
                    new DeviceModelHistoryDao(GatewayServer.getInstance().getContext()).addModelHisotry(dm3);
                }
            }

            if(!StringUtil.isNullOrEmpty(way4)){
                dm4 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId, Number,way4);
                if(dm4 != null){
                    dm4.setDeviceStatus(deviceStatus4);
                    dm4.setSignal(signal);
                    dm4.setOnlineStatus(onlineStatus);
                    dm4.setIfAnyone(ifAnyone);
                    dmd.add(dm4);

                    dm4 = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),dm4.getDeviceId(), dm4.getDeviceNumber(),way4);
                    list.add(dm4);

                    //统计耗电量
                    new DeviceModelHistoryDao(GatewayServer.getInstance().getContext()).addModelHisotry(dm4);
                }
            }

        }
        updateData();

    }

    private void updateData(){
        BoxModel bm = new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox();
        //构造反馈数据
        DeviceStatusReply deviceStatusReply = new DeviceStatusReply();
        deviceStatusReply.setCurrentBoxCpuId(bm.getBoxCpuId());
        deviceStatusReply.setUserName(new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox().getUserName());
        deviceStatusReply.setDeviceStatus(list);

        JSONObject jsonObject = (JSONObject)JSON.toJSON(deviceStatusReply);
        list.clear();

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }



    public boolean checkSceneList(String deviceStatus,String deviceNumber,String deviceId){
        boolean flag=false;
        ConditionStatusModelDao csmd=new ConditionStatusModelDao(context);
        SceneModelDao smd = new SceneModelDao(context);
        List<SceneModel> sceneModelList = smd.getList();
        String Status=deviceStatus;
        String number=deviceNumber;
        if (sceneModelList!=null || sceneModelList.size()!=0){
        for(SceneModel sModel : sceneModelList){
            for(ConditionStatusModel csm : sModel.getStatusModelList()){
                if((csm.getDeviceStatus().equals(Status)) && (csm.getDeviceNumber().equals(number)) && csm.getDeviceId().equals(deviceId)){
                    flag = true;
                }else if ((!csm.getDeviceStatus().equals(Status)) && (csm.getDeviceNumber().equals(number)) && csm.getDeviceId().equals(deviceId)){
                    SceneModel sceneModel = new SceneModel();
                    SceneModelDao sceneModelDao = new SceneModelDao(SceneServer.getInstance().getContext());
                    sceneModel = sceneModelDao.getSceneModelOnly(sModel.getSceneName());
                    sceneModel.setStatusCycleFlag("true");
                    sceneModelDao.add(sceneModel);
                }
            }
        }
        }
        return flag;
    }


    public boolean SensorSceneList(int mPM25Value,int  mLightValue, int mHumidityValue ,int mAirValue ,double mTemperature,String currentBoxCpuId,String deviceNumber,String way) {
        SceneModelDao smd = new SceneModelDao(context);
        DeviceModelDao dmd = new DeviceModelDao(context);
        DeviceModel deviceModel;
        boolean flag=false;
        List<SceneModel> sceneModelList = smd.getList();
        SceneModel sceneModel = new SceneModel();
        SceneModelDao sceneModelDao = new SceneModelDao(SceneServer.getInstance().getContext());
        if(sceneModelList!=null || sceneModelList.size()!=0 ) {
            for (SceneModel sModel : sceneModelList) {
                for (ConditionSensorModel csm : sModel.getSensorModelList()) {
                    //判断设备主机ID跟设备编号以及路数是否属于当前情景所绑定的探测器
                    if (currentBoxCpuId.equals( csm.getBoxCpuId()) && deviceNumber.equals(csm.getDeviceNumber() )&& way.equals(csm.getWay())){
                    sceneModel=sceneModelDao.getSceneModelOnly( csm.getSceneName());
                        if (sModel.getSensorModelList()!=null || sModel.getSensorModelList().size()!=0) {
                            if (csm.getSceneName().equals(sModel.getSceneName())) {
                                switch (csm.getConditionSubType()) {

                                    case 0://0 二氧化碳

                                        break;
                                    case 1://1 空气质量
                                       int AirValue= Integer.parseInt( csm.getCheckAirValue());
                                        deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(csm.getBoxCpuId(),csm.getDeviceId(),csm.getDeviceNumber(),csm.getWay());
                                        int ariQuality =  deviceModel.getAriQuality();
                                        if ("0".equals(csm.getConditionCheckModel()) ){
                                            //大于
                                            if (mAirValue > AirValue  && ariQuality <= AirValue){
                                                flag=true;
                                            }else if (mAirValue <= AirValue){
                                                    if(sceneModel.getStatusCycleFlag()!="true"){
                                                        sceneModel.setStatusCycleFlag("true");
                                                        sceneModelDao.add(sceneModel);
                                                    }
                                            }
                                        }else if ("1".equals(csm.getConditionCheckModel())){
                                            //等于
                                            if (mAirValue == AirValue && ariQuality != AirValue){
                                                flag=true;
                                            }else if (mAirValue != AirValue){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("2".equals(csm.getConditionCheckModel())){
                                            //小于
                                            if (mAirValue < AirValue && ariQuality > AirValue){
                                                flag=true;
                                            }else if (mAirValue >= AirValue){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }
                                        break;
                                    case 2://2 PM2.5
                                         deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(csm.getBoxCpuId(),csm.getDeviceId(),csm.getDeviceNumber(),csm.getWay());
                                        int oldPm25 =  deviceModel.getPm25();

                                        if ("0".equals(csm.getConditionCheckModel())){
                                            //大于
                                            if (mPM25Value > csm.getCheckPM25Value() && oldPm25 < csm.getCheckPM25Value() ){
                                                flag=true;
                                            }else if (mPM25Value <= csm.getCheckPM25Value()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("1".equals(csm.getConditionCheckModel())){
                                            //等于&
                                            if (mPM25Value == csm.getCheckPM25Value() && oldPm25 != csm.getCheckPM25Value()){
                                                flag=true;
                                            }else if (mPM25Value != csm.getCheckPM25Value()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("2".equals(csm.getConditionCheckModel())){
                                            //小于
                                            if (mPM25Value < csm.getCheckPM25Value() && oldPm25 > csm.getCheckPM25Value()){
                                                flag=true;
                                            }else if (mPM25Value >= csm.getCheckPM25Value()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }

                                        break;
                                    case 3://3 光照
                                         deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(csm.getBoxCpuId(),csm.getDeviceId(),csm.getDeviceNumber(),csm.getWay());
                                        int SunLight =  deviceModel.getSunLight();
                                        if ("0".equals(csm.getConditionCheckModel())){
                                            //大于
                                            if (mLightValue > csm.getCheckLightValue() &&  SunLight <= csm.getCheckLightValue()){
                                                flag=true;
                                            }else if (mLightValue <= csm.getCheckLightValue()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("1".equals(csm.getConditionCheckModel())){
                                            //等于
                                            if (mLightValue == csm.getCheckLightValue() && SunLight != csm.getCheckLightValue()){
                                                flag=true;
                                            }else if (mLightValue != csm.getCheckLightValue()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("2".equals(csm.getConditionCheckModel())){
                                            //小于
                                            if (mLightValue < csm.getCheckLightValue() && SunLight >= csm.getCheckLightValue()){
                                                flag=true;
                                            }else if (mLightValue >= csm.getCheckLightValue()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }

                                        break;
                                    case 4://4 温湿度
                                        deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(csm.getBoxCpuId(),csm.getDeviceId(),csm.getDeviceNumber(),csm.getWay());
                                        int humidity =  deviceModel.getHumidity();
                                        double temperature =  deviceModel.getTemperature();
                                        //湿度
                                        if (csm.getCheckHumidityValue()!=-1314){

                                        if ("0".equals(csm.getConditionCheckModel())){
                                            //大于
                                            if (mHumidityValue > csm.getCheckHumidityValue() &&  humidity < csm.getCheckHumidityValue()){
                                                flag=true;
                                            }else if (mHumidityValue <= csm.getCheckHumidityValue()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("1".equals(csm.getConditionCheckModel())){
                                            //等于
                                            if (mHumidityValue == csm.getCheckHumidityValue()&&  humidity != csm.getCheckHumidityValue()){
                                                flag=true;
                                            }else if (mHumidityValue != csm.getCheckHumidityValue()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }else if ("2".equals(csm.getConditionCheckModel())){
                                            //小于
                                            if (mHumidityValue < csm.getCheckHumidityValue() &&  humidity > csm.getCheckHumidityValue()){
                                                flag=true;
                                            }else if (mHumidityValue >= csm.getCheckHumidityValue()){
                                                if(sceneModel.getStatusCycleFlag()!="true"){
                                                    sceneModel.setStatusCycleFlag("true");
                                                    sceneModelDao.add(sceneModel);
                                                }
                                            }
                                        }

                                        }

                                        //温度
                                        if (csm.getCheckTemperatureValue()!=-1314) {
                                            if ("0".equals(csm.getConditionCheckModel())) {
                                                //大于
                                                if (mTemperature > csm.getCheckTemperatureValue() && temperature < csm.getCheckTemperatureValue()) {
                                                    flag = true;
                                                } else if (mTemperature <= csm.getCheckTemperatureValue()) {
                                                    if (sceneModel.getStatusCycleFlag() != "true") {
                                                        sceneModel.setStatusCycleFlag("true");
                                                        sceneModelDao.add(sceneModel);
                                                    }
                                                }
                                            } else if ("1".equals(csm.getConditionCheckModel())) {
                                                //等于
                                                if (mTemperature == csm.getCheckTemperatureValue() && temperature != csm.getCheckTemperatureValue()) {
                                                    flag = true;
                                                } else if (mTemperature != csm.getCheckTemperatureValue()) {
                                                    if (sceneModel.getStatusCycleFlag() != "true") {
                                                        sceneModel.setStatusCycleFlag("true");
                                                        sceneModelDao.add(sceneModel);
                                                    }
                                                }
                                            } else if ("2".equals(csm.getConditionCheckModel())) {
                                                //小于
                                                if (mTemperature < csm.getCheckTemperatureValue() && temperature > csm.getCheckTemperatureValue()) {
                                                    flag = true;
                                                } else if (mTemperature >= csm.getCheckTemperatureValue()) {
                                                    if (sceneModel.getStatusCycleFlag() != "true") {
                                                        sceneModel.setStatusCycleFlag("true");
                                                        sceneModelDao.add(sceneModel);
                                                    }
                                                }
                                            }
                                        }
                                        break;
                                    case 5://5 风雨传感器

                                        break;
                                    case 6://6 报警类设备

                                        break;

                                    default:
                                        break;
                                }
                            }
                        }
                }
                }

            }
        }
        return flag;
    }




}
